import { envDeviceControllerTreeDevice } from '@/services/ess/deviceEnv';
import { Input, Tree } from 'antd';
import React, { useEffect, useState } from 'react';
import { useIntl, useModel } from 'umi';
import Style from '../index.less';
const { Search } = Input;

interface treeProps {
  handleClick?: () => void;
}

const App: React.FC<treeProps> = ({ handleClick }) => {
  const intl = useIntl();
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [selectNodeID, setselectNodeID] = useState<any>('');

  const [treeData, setTreeData] = useState([]); //tree数据   这里数据接口获取 结构同上  就不再写了  后面直接用
  const [searchData, setsearchData] = useState(''); //搜索
  const [tree, setTree] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);

  const updataSearch = (e) => {
    //更新input值
    setsearchData(e.target.value);
  };

  //  const getParentKey = (key, tree) => { //传入当前节点key,返回父节点key
  //   let parentKey;
  //   for (let i = 0; i < tree.length; i++) {
  //     const node = tree[i];
  //     if (node.children) {
  //       if (node.children.some(item => item.key === key)) {
  //         parentKey = node.key;
  //       } else if (getParentKey(key, node.children)) { //如果没找到 继续向下匹配 递归调用
  //         parentKey = getParentKey(key, node.children);
  //       }
  //     }
  //   }
  //   return parentKey;
  // };
  const fliterData = (data) =>
    data.map((item) => {
      //过滤数据 将input的搜索值 高亮显示
      const index = item.title.indexOf(searchData);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchData.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: 'red' }}>{searchData}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return { title, key: item.key, children: fliterData(item.children) };
      }
      return {
        title,
        key: item.key,
      };
    });

  let keyArr2 = []; //存放匹配key 的数组
  //传入input value值 模糊搜索 匹配key值数组
  const getKey = (value, data) => {
    data.forEach((item) => {
      if (item.title.indexOf(value) > -1) {
        keyArr2.push(item.key);
      }
      if (item.children) {
        getKey(value, item.children);
      }
    });

    return keyArr2.filter((item, i, self) => item && self.indexOf(item) === i);
    //过滤数组中相同的key值
  };

  const searchValue = () => {
    //点击或者enter搜索
    let value = searchData;
    setAutoExpandParent(true);
    const expandedKey = getKey(value, tree);
    setExpandedKeys(expandedKey);
    setTreeData(fliterData(tree));
  };

  const onExpand = (expandedKeys) => {
    //展开/收起节点时触发
    setExpandedKeys(expandedKeys);
    // setAutoExpandParent(false)
  };

  const TreeSelectMethod = (selectedKeys, target) => {
    let len = target.node.pos.split('-').length;
    if (len === 4) {
      handleClick(target.node);
    }
  };

  const modifyJSON = (obj: any) => {
    if (obj === null || typeof obj !== 'object') {
      return obj;
    }

    if (Array.isArray(obj)) {
      return obj.map((item) => modifyJSON(item));
    }

    const newObj = {};
    Object.keys(obj).forEach((key) => {
      if (key === 'deviceName') {
        newObj['title'] = obj[key];
      } else if (key === 'deviceId') {
        newObj['key'] = obj[key];
      } else if (key === 'subDevices') {
        newObj['children'] = modifyJSON(obj[key]);
      } else {
        newObj[key] = modifyJSON(obj[key]);
      }
    });

    return newObj;
  };

  useEffect(() => {
    envDeviceControllerTreeDevice({ stationId: stationId }).then((res) => {
      if (res.data && res.data.length) {
        let changeVal = modifyJSON(res.data);
        setTreeData(changeVal);
        setTree(changeVal);
        if (changeVal[0]?.['children'][0]?.['children'][0]?.['key']) {
          setExpandedKeys([changeVal[0]?.['children'][0]?.['children'][0]?.['key']]);
          setselectNodeID(changeVal[0]?.['children'][0]?.['children'][0]?.['key']);
          handleClick(changeVal[0]?.['children'][0]?.['children']?.[0]);
        }
      } else {
        handleClick(null);
      }
    });
  }, []);

  return (
    <>
      <div className={Style.treeWrap}>
        <Search
          placeholder={intl.formatMessage({ id: 'siteManage.enterPlease' })}
          value={searchData}
          onChange={updataSearch}
          onSearch={searchValue}
          className={Style.tree_search}
          allowClear
        />
        {selectNodeID && (
          <Tree
            // fieldNames={{ title: 'deviceName', key: 'deviceId', children: 'subDevices' }}
            treeData={treeData}
            defaultSelectedKeys={[selectNodeID]}
            onSelect={TreeSelectMethod}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            defaultExpandAll={true}
            className={Style.tree}
          />
        )}
      </div>
    </>
  );
};

export default App;
